import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

contextBridge.exposeInMainWorld('electron', {
  ipcRenderer: {
    myPing() {
      ipcRenderer.send('ipc-example', 'ping');
    },
    inputStream(path: string) {
      console.log('inputStream: %s', path);
      ipcRenderer.send('inputStream', path);
    },
    outputStream: function(path: string, data: any) {
      let obj = { path: path, data: data };
      let msg = JSON.stringify(obj);
      console.log('outputStream: obj: ' + msg);
      ipcRenderer.send('outputStream', msg);
    },
    on(channel: string, func: (...args: unknown[]) => void) {
      const validChannels = ['ipc-example'];
      if (validChannels.includes(channel)) {
        const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
          func(...args);
        // Deliberately strip event as it includes `sender`
        ipcRenderer.on(channel, subscription);

        return () => ipcRenderer.removeListener(channel, subscription);
      }

      return undefined;
    },
    once(channel: string, func: (...args: unknown[]) => void) {
      const validChannels = ['outputStream', 'inputStream'];
      if (validChannels.includes(channel)) {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.once(channel, (_event, ...args) => {
          let str = args[0];
          console.log(str);
          let data = unwrapMessage(str);
          console.log(data);
          let arr = [];
          arr[0] = data;
          func(... arr);
        });
      }
    }
  }
});
const unwrapMessage = (message: string) => {
    let wrap = JSON.parse(message);
    return wrap.data;
}
